<?php

namespace magein\think\utils\api;

use magein\think\utils\constants\Code;
use think\db\exception\PDOException;
use think\exception\Handle;
use think\exception\RouteNotFoundException;
use think\exception\ValidateException;
use think\facade\Log;
use think\helper\Str;
use think\Response;
use Throwable;

/**
 * 接口验证参数类验证失败后会修改http请求的status_code
 *
 * 这里统一返回200，且由返回
 * {
 *      code:"",
 *      msg:"",
 *      data:"",
 * }
 */
class ApiException extends Handle
{
    public function render($request, Throwable $e): Response
    {
        // debug模式下交由系统处理
        if (env('app_debug')) {
            return parent::render($request, $e);
        }

        // 参数验证错误
        if ($e instanceof ValidateException) {
            return ApiResponse::error($e->getMessage(), Code::VALIDATE_ERROR);
        }

        // 路由不匹配的错误
        if ($e instanceof RouteNotFoundException) {
            return ApiResponse::error('请求路由地址错误', Code::ROUTE_NOT_FOUND);
        }

        $trace_id = Str::random(22);
        Log::error($trace_id);

        // 数据库执行错误
        if ($e instanceof PDOException) {
            return ApiResponse::error('服务执行异常(trace id:' . $trace_id . ')', Code::DB_QUERY_ERROR);
        }

        // 统一返回
        return ApiResponse::error('服务执行异常(trace id:' . $trace_id . ')', Code::SERVER_SYSTEM_ERROR);
    }

    public function view()
    {
        $name = request()->route('name');
        $log_path = runtime_path('exception');
        if (empty($name)) {
            $date = date('Ymd');
            $files = glob($log_path . '/' . $date . '*');
        } else {
            $files = glob($log_path . '/*.' . $name);
        }
        if ($files) {
            foreach ($files as $file) {
                $extension = pathinfo($file, PATHINFO_EXTENSION);
                $content = file_get_contents($file);
                if ($content) {
                    $content = explode("\n", $content);
                    echo '<h3>' . $extension . '</h3>';
                    foreach ($content as $item) {
                        echo '&nbsp;&nbsp;&nbsp;' . $item;
                        echo '<br/>';
                    }
                }
            }
        }
    }
}